<template>
  <div class="container">
    <el-card>
      <el-form ref="searchFormRef" :model="searchData">
        <el-form-item prop="dbname" label="数据库名称：">
          <el-select v-model="searchData.dbname" placeholder="请选择" class="search-ipt">
            <el-option v-for="item in list" :key="item.id" :label="item.dbtitle" :value="item.dbname" />
          </el-select>
          <el-button type="primary" :icon="Search" @click="handleSearch" class="search-btn">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="openDialog" type="primary" plain>
            <el-icon><CirclePlus /></el-icon>
            <span>添加最佳答案</span>
          </el-button>
        </el-form-item>
      </el-form>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :row-class-name="rowClassName"
          max-height="calc(100vh - 300px)"
        >
          <el-table-column label="序号" width="60">
            <template #default="scope">
              {{ scope.row.index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="dbtitle" label="数据库名称" width="130" />
          <el-table-column prop="question" label="问题" width="250" />
          <el-table-column prop="answer" label="答案">
            <template #default="scope">
              <ClampText :text="scope.row.answer" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-tooltip class="box-item" effect="dark" content="编辑" placement="top">
                <el-icon color="#0C6BED" size="16" @click="edit(scope.row)" class="edit-btn"><Edit /></el-icon>
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                <el-icon color="#E34D59" size="16" @click="clickDel(scope.row)"><Delete /></el-icon>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper" v-if="paginationData.total > 0">
        <div class="totalCount">共{{ paginationData.total }}项数据</div>
        <el-pagination
          background
          :layout="paginationData.layout"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogFormVisible" :title="form.qid ? '修改' : '新增'" width="700">
      <el-form :model="form">
        <el-form-item label="问题：" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" :disabled="form.qid" />
        </el-form-item>
        <el-form-item label="答案：" :label-width="formLabelWidth" class="sql-editor">
          <div class="box">
            <sql-code-edit
              :value="form.data"
              :editor-placeholder="'请输入答案'"
              :tab-size="4"
              @change="changeSqlCode"
            />
          </div>
        </el-form-item>
        <el-form-item label="" :label-width="formLabelWidth">
          <el-select v-model="form.dbname" placeholder="请选择数据库名称">
            <el-option v-for="item in list" :key="item.id" :label="item.dbtitle" :value="item.dbname" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancle">取消</el-button>
          <el-button type="primary" @click="addTable"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue"
import { ElMessage, ElLoading, ElMessageBox } from "element-plus"
import SqlCodeEdit from "@/components/SqlEdit/index.vue"
import ClampText from "@/components/ClampText/index.vue"
import { getSelList, selSave, selUpdate, selDel } from "@/api/konwledge"
import { getDbNameList } from "@/api/sql"

onMounted(() => {
  getTableData()
  getlist()
})
const searchFormRef = ref(null)
const searchData = ref({
  dbname: ""
})
const handleSearch = () => {
  paginationData.value.currentPage
  getTableData()
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

const list = ref([])
async function getlist() {
  const { code, data } = await getDbNameList()
  if (code === 200) {
    list.value = data
  }
}
const paginationData = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  layout: "prev, pager, next"
})
/** 改变当前页码 */
function handleCurrentChange(value) {
  if (paginationData.value.currentPage === value) return
  paginationData.value.currentPage = value
  getTableData()
}

const dialogFormVisible = ref(false)
const form = ref({
  name: "",
  data: "",
  dbname: ""
})
const formLabelWidth = "70px"
const tableData = ref([])
const edit = (para) => {
  dialogFormVisible.value = true
  form.value = {
    dbname: para.dbname,
    name: para.question,
    data: para.answer,
    qid: para.qid
  }
}
const clickDel = (para) => {
  ElMessageBox.confirm("确认删除当前数据吗?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delTr(para)
  })
}
async function delTr(row) {
  const { code } = await selDel({ qid: row.qid })
  if (code === 200) {
    ElMessage.success("删除成功")
    tableData.value.splice(row.index, 1)
  }
}
function rowClassName({ row, rowIndex }) {
  row.index = rowIndex
}

//实时获取sql语句
const changeSqlCode = (val) => {
  form.value.data = val
}

function openDialog() {
  Object.keys(form.value).forEach((key) => {
    form.value[key] = null
  })
  dialogFormVisible.value = true
}
function cancle() {
  Object.keys(form.value).forEach((key) => {
    form.value[key] = null
  })
  dialogFormVisible.value = false
}
async function addTable() {
  if (form.value.qid) {
    const { code } = await selUpdate({
      qid: form.value.qid,
      question: form.value.name,
      answer: form.value.data,
      dbname: form.value.dbname
    })
    if (code === 200) {
      ElMessage.success("操作成功")
    }
  } else {
    const { code } = await selSave({
      question: form.value.name,
      answer: form.value.data,
      dbname: form.value.dbname
    })
    if (code === 200) {
      ElMessage.success("操作成功")
    }
  }
  // if (code === 200) {
  //   ElMessage.success("操作成功")
  getTableData()
  form.value.name = ""
  form.value.data = ""
  form.value.dbname = ""

  dialogFormVisible.value = false
  // }
}
async function getTableData() {
  const wrap = document.getElementsByClassName("table-wrapper")[0]
  const loadingInstance = ElLoading.service({
    target: wrap,
    text: "Loading"
  })
  const { code, data } = await getSelList({
    dbname: searchData.value.dbname,
    page: paginationData.value.currentPage,
    pageSize: paginationData.value.pageSize
  })
  if (code === 200) {
    tableData.value = data.resultList
    paginationData.value.total = data.totalCount
  }
  loadingInstance.close()
}
</script>
<style lang="scss" scoped>
::v-deep(.el-form-item__content) {
  flex: none;
  width: 580px !important;
}
/* 设置表头背景色 */
::v-deep(.el-table__header-wrapper th) {
  background-color: #f5f5f5; /* 背景色 */
  color: #333; /* 文字颜色 */
  font-weight: bold; /* 加粗字体 */
}
:deep(.sql-editor .el-form-item__content) {
  display: inline-block !important;
  width: 580px;
}
.search-btn {
  margin-left: 16px;
}
.edit-btn {
  margin-right: 20px;
}
.sql-editor {
  display: block;
}
.box {
  border: 1px solid #ccc;
}
.search-wrap {
  display: flex;
  align-items: center;
}
.sel-wrap {
  font-size: 14px;
  align-items: center;
  display: flex;
  margin-right: 10px;
  .label {
    margin-right: 10px;
  }
}
.search-ipt {
  width: 250px;
}
.add-wrap {
  padding: 20px;
  display: flex;
}
.table-wrapper {
  margin-bottom: 20px;
}
.pager-wrapper {
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
